package gateway.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.List;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

/**
 * @ClassName: EngineeringChooseRule
 * @Description:
 * @Author guochuang
 * @Date 2024/7/31
 * @Version 1.0
 */
public class EngineeringChooseRule implements IChooseRule {


    @Override
    public ServiceInstance choose(ServerWebExchange exchange, DiscoveryClient discoveryClient) {
        URI originalUrl = (URI) exchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
        String instancesId = originalUrl.getHost();
        if(instancesId.equals("my-service-id")){
            if(originalUrl.getPath().contains("/files/upload")){
                try{
                    List<ServiceInstance> instances = discoveryClient.getInstances(instancesId);
                    MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
                    String uuid = queryParams.get("uuid").get(0);
                    int hash = uuid.hashCode() >>> 16 ;
                    int index = hash % instances.size();
                    return instances.get(index);
                }catch (Exception e){
                    //do nothing
                }
            }
        }

        return null;
    }

}
